package com.ruoyi.merchant.controller;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.merchant.annotation.DictFilter;
import com.ruoyi.merchant.domain.*;
import com.ruoyi.merchant.dto.CustomerHistoryMedicalDto;
import com.ruoyi.merchant.service.*;
import com.ruoyi.merchant.vo.CustomerBaseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 客户基本信息Controller
 * 
 * @author chengxin.ju
 * @date 2023-12-12
 */
@Slf4j
@RestController
@RequestMapping("/customer")
public class CustomerBaseController extends BaseController
{
    @Autowired
    private ICustomerBaseService customerBaseService;
    @Autowired
    private IBaseDeviceInfoService baseDeviceInfoService;
    @Autowired
    private IDeviceCategoryService deviceCategoryService;
    @Autowired
    private IDeviceModelService deviceModelService;
    @Autowired
    private ICustomerHistoryMedicalService customerHistoryMedicalService;


    /**
     * 查询客户基本信息列表
     */
    @GetMapping("/list")
    @DictFilter(dataType = "page")
    public TableDataInfo list(CustomerBase customerBase)
    {
        startPage();
        customerBase.setDel(0L);
        List<CustomerBaseVo> list = customerBaseService.selectCustomerBaseList(customerBase);
        if (CollectionUtils.isNotEmpty(list)){
            list = list.stream().map(item->{
                BaseDeviceInfo baseDeviceInfo = new BaseDeviceInfo();
                baseDeviceInfo.setCustomerId(item.getId());
                baseDeviceInfo.setDel(0L);
                List<BaseDeviceInfo> baseDeviceInfos = baseDeviceInfoService.selectBaseDeviceInfoList(baseDeviceInfo);
                item.setBaseDeviceInfoList(baseDeviceInfos);
                try {
                    if (item.getCustomerBirthday() != null){
                        item.setAge(Long.valueOf(DateUtils.getAge(item.getCustomerBirthday())));
                    }
                    if (CollectionUtils.isNotEmpty(item.getBaseDeviceInfoList())){
                        List<BaseDeviceInfo> collect = item.getBaseDeviceInfoList().stream().map(obj -> {
                            String type = obj.getType();
                            DeviceCategory deviceCategory = deviceCategoryService.selectDeviceCategoryById(type);
                            obj.setType_text(deviceCategory.getName());
                            String equipmentType = obj.getEquipmentType();
                            DeviceModel deviceModel = deviceModelService.selectDeviceModelById(equipmentType);
                            obj.setEquipmentType_text(deviceModel.getName());
                            if (obj.getStatus() != null && obj.getStatus().longValue() == 0){
                                obj.setStatus_text("激活");
                            }else {
                                obj.setStatus_text("冻结");
                            }
                            return obj;
                        }).collect(Collectors.toList());
                        item.setBaseDeviceInfoList(collect);
                    }

                    CustomerHistoryMedical customerHistoryMedical = new CustomerHistoryMedical();
                    customerHistoryMedical.setCustomerId(item.getId());
                    List<CustomerHistoryMedical> customerHistoryMedicalList = customerHistoryMedicalService.selectCustomerHistoryMedicalList(customerHistoryMedical);
                    if (CollectionUtils.isNotEmpty(customerHistoryMedicalList)){
                        item.setHistoryMedicalId(customerHistoryMedicalList.get(0).getId());
                    }
                } catch (Exception e) {
                    item.setAge(0L);
                    log.error(e.getMessage(),e);
                }
                return item;
            }).collect(Collectors.toList());
        }
        return getDataTable(list);
    }


//    /**
//     * 查询客户基本信息列表
//     */
//    @GetMapping("/list/v2")
//    @DictFilter(dataType = "page")
//    public TableDataInfo listV2(CustomerBase customerBase)
//    {
//        startPage();
//        List<CustomerBaseVo> list = customerBaseService.selectCustomerBaseListV2(customerBase);
//        return getDataTable(list);
//    }

    /**
     * 导出客户基本信息列表
     */
    @Log(title = "客户基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustomerBase customerBase)
    {
        List<CustomerBaseVo> list = customerBaseService.selectCustomerBaseList(customerBase);
        ExcelUtil<CustomerBaseVo> util = new ExcelUtil<CustomerBaseVo>(CustomerBaseVo.class);
        util.exportExcel(response, list, "客户基本信息数据");
    }

    @Autowired
    private IOrganService organService;
    @Autowired
    private ICustomerHistoryMedicalDiseaseService customerHistoryMedicalDiseaseService;


    /**
     * 获取客户基本信息详细信息
     */
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfo(CustomerBase customerBase)
    {
        List<CustomerBaseVo> customerBaseVos = customerBaseService.selectCustomerBaseList(customerBase);
        if(CollectionUtils.isNotEmpty(customerBaseVos)){
            CustomerBaseVo customerBaseVo = customerBaseVos.get(0);
            if (StringUtils.isNoneBlank(customerBaseVo.getCustomerOrg())){
                Organ organ = organService.selectOrganById(customerBaseVo.getCustomerOrg());
                customerBaseVo.setOrgName(organ.getName());
            }
            CustomerHistoryMedical customerHistoryMedical = new CustomerHistoryMedical();
            customerHistoryMedical.setCustomerId(customerBaseVo.getId());
            List<CustomerHistoryMedical> customerHistoryMedicalList = customerHistoryMedicalService.selectCustomerHistoryMedicalList(customerHistoryMedical);
            if (CollectionUtils.isNotEmpty(customerHistoryMedicalList)){
                CustomerHistoryMedicalDto customerHistoryMedicalDto = new CustomerHistoryMedicalDto();
                BeanUtils.copyProperties(customerHistoryMedicalList.get(0),customerHistoryMedicalDto);

                CustomerHistoryMedicalDisease customerHistoryMedicalDisease = new CustomerHistoryMedicalDisease();
                customerHistoryMedicalDisease.setHistoryId(customerHistoryMedicalDto.getId());
                List<CustomerHistoryMedicalDisease> customerHistoryMedicalDiseaseList = customerHistoryMedicalDiseaseService.selectCustomerHistoryMedicalDiseaseList(customerHistoryMedicalDisease);
                if (CollectionUtils.isNotEmpty(customerHistoryMedicalDiseaseList)){
                    customerHistoryMedicalDto.setCustomerHistoryMedicalDiseaseList(customerHistoryMedicalDiseaseList);
                }
                customerBaseVo.setCustomerHistoryMedicalDto(customerHistoryMedicalDto);
            }
            return success(customerBaseVo);
        }
        return error("用户不存在");
    }

    /**
     * 新增客户基本信息
     */
    @Log(title = "客户基本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustomerBase customerBase) throws Exception {
        CustomerBase param = new CustomerBase();
        param.setCustomerCard(customerBase.getCustomerCard());
        param.setDel(0L);
        List<CustomerBaseVo> customerBaseVoList = customerBaseService.selectCustomerBaseList(param);
        if (CollectionUtils.isNotEmpty(customerBaseVoList)){
            return error("家人已存在不能新增");
        }
        return success(customerBaseService.insertCustomerBase(customerBase));
    }






    /**
     * 修改客户基本信息
     */
    @Log(title = "客户基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CustomerBase customerBase) throws Exception {
        return success(customerBaseService.updateCustomerBase(customerBase));
    }


    /**
     * 删除设备信息
     */
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("id") String id) throws Exception {
        CustomerBase customerBase = new CustomerBase();
        customerBase.setId(id);
        //删除标志置位 1 即删除
        customerBase.setDel(1L);
        customerBaseService.updateCustomerBase(customerBase);
        return success();
    }

}
